<?php

require_once 'src/IPDF2SWFService.php';
require_once 'src/dao/PDF2SWFOptionDao.php';

class PDF2SWFService implements IPDF2SWFService {
	protected $result;
	protected $pid;//process id;
	protected $command = "C:\SWFTools\pdf2swf.exe 
	-o C:\SWFTools\ChineseTest.swf 
	-t C:\SWFTools\ChineseTest.pdf 
	-s languagedir=C:\SWFTools\xpdf-chinese-simplified\xpdf\chinese-simplified\ ";
	public function PDF2SWFService()
	{
		//TODO:
	}
	
	public function pdf2swf(PDF2SWFOptionDao $option,$timeout=60,$sleep=2)
	{
		// First, execute the process, get the process ID 
		$this->pid = $this->PsExec($this->command);
		if($this->pid==false)
		{
			return false;
		}
		$cur = 0;
		// Second,loop for $timeout seconds checking if process is running.
		while($cur<$timeout)
		{
			sleep($sleep);
			//If process is no longer running,return true;
			echo "\n----$cur----\n";
			if(!$this->PsExists($this->pid))
			{
				return true;//Process id must be existed,success!
			}
		}
		//If process is still running after timeout,kill the process and return false;
		$this->PsKill($this->$pid);
		return false;
	}
	
	private function PsExec($commandJob) {

        $command = $commandJob.' > /dev/null 2>&1 & echo $!';
        exec($command ,$op);
        $pid = (int)$op[0];

        if($pid!="") return $pid;

        return false;
    }

   private function PsExists($pid) {

        exec("ps ax | grep $pid 2>&1", $output);

        while(list(,$row) = each($output) ) {

                $row_array = explode(" ", $row);
                $check_pid = $row_array[0];

                if($pid == $check_pid) {
                        return true;
                }

        }

        return false;
    }
	
    private function PsKill($pid) {
        exec("kill -9 $pid", $output);
    } 
}

?>